package com.bwie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwie.config.ConsultInfo;
import com.bwie.config.FreemarkerUtil;
import com.bwie.config.R;
import com.bwie.pojo.Consult;
import com.bwie.pojo.Content;
import com.bwie.pojo.Personnel;
import com.bwie.pojo.Type;
import com.bwie.service.ConsultService;
import com.bwie.service.ContentService;
import com.bwie.service.PersonnelService;
import com.bwie.service.TypeService;
import freemarker.template.TemplateException;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Auther:${涛}
 * @Date:2024/9/2 10:04
 * @Description: personnelController
 * @Version 1.0.0
 */
@RestController
@RequestMapping("/car")
public class ConsultController {

    @Autowired
    private ConsultService consultService;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    private ContentService contentService;


    @Autowired
    private TypeService typeService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    //访客列表页面

    @PostMapping("/save")
    public R save() {
        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(ConsultInfo.class);
        boolean exists = indexOperations.exists();
        if (exists) {
            indexOperations.delete();
        }
        indexOperations.create();

        Document mapping = indexOperations.createMapping();
        indexOperations.putMapping(mapping);
        return R.OK("ES表格创建成功");
    }

    @PostMapping("/consultList")
    public R consultList(@RequestBody Consult consult) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        //查询所有
        boolQueryBuilder.must(QueryBuilders.matchAllQuery());

        //高亮查询
        if (!StringUtils.isEmpty(consult.getName())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("name", consult.getName()));
        }


        //分页
        int pageNum = 0;
        if (consult.getPageNum() > 0) {
            pageNum = consult.getPageNum() - 1;
        }
        PageRequest request = PageRequest.of(pageNum, consult.getPageSize());

        HighlightBuilder highlightBuilder = new HighlightBuilder();

        highlightBuilder.field("name").preTags("<font color=red>").postTags("</font>");


        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withPageable(request).withHighlightBuilder(highlightBuilder).withQuery(boolQueryBuilder);


        SearchHits<ConsultInfo> searchHits = elasticsearchRestTemplate.search(nativeSearchQueryBuilder.build(), ConsultInfo.class);
        ArrayList<ConsultInfo> infoArrayList = new ArrayList<>();

        long total = searchHits.getTotalHits();

        for (SearchHit<ConsultInfo> searchHit : searchHits.getSearchHits()) {
            List<String> name = searchHit.getHighlightField("name");
            ConsultInfo content = searchHit.getContent();
            for (String s : name) {
                if (name != null && name.size() > 0) {
                    name.get(0);
                    content.setName(s);
                }
            }
            infoArrayList.add(content);
//            TouristInfo content = searchHit.getContent();
//            List<String> name = searchHit.getHighlightField("touristName");
//            for (String s : name) {
//                if (name != null && name.size() > 0) {
//                    name.get(0);
//                    content.setTouristName(s);
//                }
//            }
//            tourists.add(content);
        }

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("infoArrayList", infoArrayList);
        hashMap.put("total", total);
        hashMap.put("pageNum", pageNum);
        hashMap.put("pageSize", consult.getPageSize());
        return R.OK(hashMap);
    }

    //事由异步获取后台数据进行展示（3分）
    @PostMapping("/contentList")
    public R contentList() {
        List<Content> list = contentService.list();
        return R.OK(list);
    }

    //拜访部门下拉框从数据库中进行获取
    @PostMapping("/tree")
    public R tree() {
        List<Type> typeList = typeService.treeList();
        return R.OK(typeList);
    }

    //根据id查询要输出的数据
    @PostMapping("/typeById/{id}")
    public R typeById(@PathVariable(name = "id") Integer id) {

        LambdaQueryWrapper<Type> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Type::getTestId, id);

        List<Type> list = typeService.list(wrapper);
        return R.OK(list);
    }

    @PostMapping("/consAdd")
    public R consAdd(@RequestBody Consult consult) throws TemplateException, IOException {
        consultService.save(consult);


//(8)户点击保存，MQ异步发消息。确保消息不丢失（4分）
//(9)MQ异步发消息。确保消息的幂等（4分）
//(10)MQ异步发消息, 防止消息重复发送（4分）
        String msgId = UUID.randomUUID().toString();
        stringRedisTemplate.opsForValue().set(msgId, consult.getId() + "");
        rabbitTemplate.convertAndSend("2202-09-02", "", msgId);

        List<Consult> list = consultService.list();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("list", list);

        String url = "D:\\test\\file\\bb" + ".html";

        FreemarkerUtil freemarkerUtil = new FreemarkerUtil();
        freemarkerUtil.createHtml(hashMap, "bb", url);

        return R.OK("添加成功");

    }

    //审核
    @PostMapping("/consultById/{id}")
    public R consAdd(@PathVariable(name = "id") Integer id) {
        //（6）击审核通过，则状态修改为审核通过（3分）
        Consult byId = consultService.getById(id);
        byId.setStatus(1);
        consultService.updateById(byId);
        return R.OK("审核成功");

    }


}


